// pages/login.js 
// 登录页面
/*
import React, { useState } from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input,message } from 'antd'; // 导入antd组件
import welcomeStyles from '../styles/welcomePage.module.css';
import loginStyles from '../styles/loginPage.module.css'; // 导入CSS样式文件
import { Link, useRouter } from 'next/router';
import axios from 'axios';
const Login = () => {
  const router = useRouter();
  const [error, setError] = useState('');
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  
  const handleSubmit = async () => {
  
    //values.preventDefault();
    try {
      // 发送请求到后端登录 API
      const response = await axios.post("/api/user/login",{
        username:username,
        password: password,
      });
      // 假设后端返回的 token 在 response.data.token 中
      // 保存 token
      localStorage.setItem('token', response.data.data.token); // 存储token
      message.success('登录成功');
      router.push('/main'); 
     
    } catch (error) {
      if (error.response) {
        const { status, data } = error.response;
        if (status === 401) {
          message.error('登录失败，用户名或密码错误');
        } else if (status === 400) {
          message.error(data.message || '登录失败');
        } else {
          message.error('登录失败，发生未知错误');
        }
      } else if (error.request) {
        message.error('登录失败，服务器未响应');
      } else {
        message.error('登录失败，请求失败');
      }
    }
  };

  return (
    <div className={welcomeStyles.backgroundContainer}> 
    <div className={loginStyles.loginForm}>
      <Form
        name="normal_login"
        className="login-form"
        initialValues={{
          remember: true,
        }}
       // onFinish={handleSubmit}
      >
        <Form.Item
          name="username"
          rules={[
            {
              required: true,
              message: 'Please input your Username!',
            },
          ]}
        >
          <Input
          type="text"
    value={username}
    onChange={(e) => setUsername(e.target.value)}
    prefix={<UserOutlined className="site-form-item-icon" />}
    placeholder="Username"
  />
        </Form.Item>
        <Form.Item
          name="password"
          rules={[
            {
              required: true,
              message: 'Please input your Password!',
            },
          ]}
        >
          <Input
            prefix={<LockOutlined className="site-form-item-icon" />}
            type="password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            placeholder="Password"
          />
        </Form.Item>
        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>Remember me</Checkbox>
          </Form.Item>
          <a className={loginStyles.loginFormForgot} href="/findPassword">
            Forgot password
          </a>
        </Form.Item>

        <Form.Item>
          <Button type="primary" onClick={handleSubmit} className={loginStyles.loginFormButton}>
            Log in
          </Button>
          Or <a href="#" onClick={() => router.push('/register1')}>register now!</a> 
        </Form.Item>
      </Form>
      {error && <div className={loginStyles.error}>{error}</div>}
    </div>
    </div>
  );
};

export default Login;
*/
import React from 'react';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { Button, Checkbox, Form, Input,message } from 'antd';
import welcomeStyles from '../styles/welcomePage.module.css';
import loginStyles from '../styles/loginPage.module.css'; // 导入CSS样式文件
import { Link, useRouter } from 'next/router';
import axios from 'axios';

const Login = () => {
  const router = useRouter(); // 使用useRouter钩子获取路由实例

  const onFinish = (values) => {
    console.log('Request Body:', values); // 打印请求体内容
    axios.post('/api/user/login', values)
      .then((response) => {
        console.log('Success:', response.data);
        const token = response.data.data.token;
        // 将令牌存储在localStorage中
        localStorage.setItem('token', token);
       
        message.success('登录成功');
        // 使用router.push来导航到/main页面
        router.push('/main'); 
      })
      .catch((error) => {
        console.log('Error:', error);
        // 登录失败时的处理
        if (error.response) {
          // 服务器返回了错误响应
          const errorMessage = error.response.data.msg || '登录失败';
          message.error(errorMessage);
        } else if (error.request) {
          // 请求已发出，但没有收到响应
          message.error('请求失败，请检查网络连接');
        } else {
          // 发送请求时出了问题
          message.error('请求失败，请检查后端服务是否可用');
        }
      });
  };

  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };

  return (
    <div className={welcomeStyles.backgroundContainer}> {/* 加入背景图片 */}
    <div className={loginStyles.loginForm}>
    <Form
      name="normal_login"
      className="login-form"
      initialValues={{
        remember: true,
      }}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <Form.Item
        name="username"
        rules={[
          {
            required: true,
            message: 'Please input your Username!',
          },
        ]}
      >
        <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="Username" />
      </Form.Item>
      <Form.Item
        name="password"
        rules={[
          {
            required: true,
            message: 'Please input your Password!',
          },
        ]}
      >
        <Input
          prefix={<LockOutlined className="site-form-item-icon" />}
          type="password"
          placeholder="Password"
        />
      </Form.Item>
      <Form.Item>
        <Form.Item name="remember" valuePropName="checked" noStyle>
          <Checkbox>Remember me</Checkbox>
        </Form.Item>
        
        <a className={loginStyles.loginFormForgot} href="/findPassword">
          Forgot password
        </a>
      </Form.Item>

      <Form.Item>
        <Button type="primary" htmlType="submit" className={loginStyles.loginFormButton}>
          Log in
        </Button>
        Or <a href="/register1">register now!</a>
      </Form.Item>
    </Form>
    </div>
  </div>
  );
};
export default Login;